﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using TimKen.BussLogic;
using TimKen.DataEntity;
using TimKen.App;
namespace TimKen.Web.Admin.UserAccount
{
    public partial class User_Add : TimKen.App.AdminPage
    {
        TimKen.BussLogic.CustomerManager cm = new TimKen.BussLogic.CustomerManager();
        TimKen.BussLogic.UserAccountManager uab = new TimKen.BussLogic.UserAccountManager();
        TimKen.BussLogic.WebUserManager wum = new WebUserManager();
        string userName;
        public override string ActionCode
        {
            get
            {
                return "85";
            }
        }
      
        protected void Page_Load(object sender, EventArgs e)
        {
            userName = Request.QueryString["UserName"] ?? "";

            //if (!IsInRoleAdmin())
            //{
            //    AuthorityFailed();
            //}
            if (!this.IsPostBack)
            {
                WebUser.Visible = false;
                BindControl();
                BindResources();
 
                if (!string.IsNullOrEmpty(userName))
                {
                    TimKen.DataEntity.UserAccount ua = new TimKen.DataEntity.UserAccount();
                    ua = uab.GetModel(userName);
                    if (ua != null)
                    {
                        txtEmail.Text = ua.Email;
                        txtPhone.Text = ua.Phone;
                        txtRealName.Text = ua.RealName;
                        txtUserName.Text = ua.UserName;
                        txtUserName.Enabled = false;
                        txtPassword.Text = ua.Password;
                        dplRole.SelectedValue = ua.RoleID.ToString();
                        dplCompanyID.SelectedValue = ua.CustomerID.ToString();
                     

                        //添加by miaozy  否则编辑时没有效果
                        ViewState["Password"] = ua.Password;

                        if (ua.RoleID == 2) {
                            this.panelPoints.Visible = true;
                            this.txtPoints.Text = ua.Points.ToString();
                        }

                    }
                    else
                    {
                        txtUserName.Text = GetLangString("FindNoUser");
                        txtUserName.Enabled = false;
                    }
                }
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                TimKen.DataEntity.UserAccount ua = new TimKen.DataEntity.UserAccount();
                ua.CreateDate = DateTime.Now;
                ua.CreatorID = 0;
                ua.RoleID = Int32.Parse(dplRole.SelectedValue);


                if(ua.RoleID != 1)
                ua.CustomerID = Int32.Parse(dplCompanyID.SelectedValue);

                if (ua.RoleID == 2)
                    ua.Points = Int32.Parse(this.txtPoints.Text);


                ua.Email = txtEmail.Text.Trim();
                if ((txtPassword == null || txtPassword.Text == "") && ViewState["Password"] != null)
                {
                    ua.Password = ViewState["Password"].ToString();
                }
                else
                {
                    ua.Password = txtPassword.Text;
                }
                ua.LastUpdatePwd = DateTime.Now;
                ua.Phone = txtPhone.Text;
                ua.RealName = txtRealName.Text;
                ua.UserName = txtUserName.Text.Trim().ToLower();
           

                //此处如果存在同名的前台自注册帐号,则强制删除帐号,以为是相互的转换.有问题
                if (wum.Exists(ua.UserName) && (dplRole.SelectedValue == "2" || dplRole.SelectedValue == "3") && !uab.Exists(ua.UserName))
                    //从web用户转入UserAccount
                {
                    wum.Delete(ua.UserName);
                    uab.Add(ua);

                    Tools.SendCreateCustomerEmail(ua.UserName);

                    //Alert(GetLangString("SaveSuccessful"));
                    Response.Redirect("/Admin/UserAccount/User_List.aspx", false);
                    //TODO:这句跳转的修改尚未发布，alert失败
                }
                else
                {
                    if (string.IsNullOrEmpty(userName))
                    {
                        uab.Add(ua);
                    }
                    else
                    {
                        uab.Update(ua);
                    }
                    Response.Redirect("/Admin/UserAccount/User_List.aspx",false);
                }

            }
            catch (CstmException ce)
            {
                Alert(ce.Message);
            }
        }

        private void BindControl()
        {
            dplCompanyID.DataSource = cm.GetEnableCustomerNameAndID("");

            if (LanguageID == (int)LanguageEnum.Chinese)
                dplCompanyID.DataTextField = "CardCode";

            else
                dplCompanyID.DataTextField = "CardCode";

            dplCompanyID.DataValueField = "CustomerID";
            dplCompanyID.DataBind();

            dplRole.DataSource = uab.GetRoles(this.LanguageID);
            dplRole.DataTextField = "RoleName";
            dplRole.DataValueField = "RoleID";

            dplRole.DataBind();

            dplRole.Items[1].Selected = true;
        }

        protected void BindResources()
        {
            btnSave.Text = GetLangString("Save");
             
            btnSearch.Text = GetLangString("Search");
        }

        protected void lbtSelectUser_Click(object sender, EventArgs e)
        {
            WebUser.Visible = true;
            BindData();

        }

        protected void BindData()
        {
            DataSet ds = wum.GetPageList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, txtWebUserName.Text, txtWebRealName.Text, txtCompany.Text);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0]["total"]);
            this.grdWebUser.DataSource = ds;
            this.grdWebUser.DataBind();
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 0;
            BindData();
        }
        protected void grdWebUser_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string userID = e.CommandArgument.ToString();

            if (e.CommandName == "SelectEvent")
            {
                //wum.Delete(userID);
                //BindData();
                TimKen.DataEntity.WebUser wu = wum.GetModel(userID);
                txtUserName.Text = wu.UserName;
                txtUserName.Enabled = false;
                txtRealName.Text = wu.RealName;
                txtEmail.Text = wu.Email;
                ViewState["Password"] = wu.Password;
                txtPassword.Visible = false;
                txtPhone.Text = wu.Phone;

                WebUser.Visible = false;
            }

        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }
    }
}
